import bisect


class Solution(object):
    def minSumOfLengths(self, arr, target):
        ans = []
        n = len(arr)
        left = 0
        right = 0
        now = 0
        while right < n:
            now += arr[right]
            while now > target:
                now -= arr[left]
                left += 1
            if now == target:
                ans.append([left, right])
            right += 1
        m = len(ans)
        min_len = float('inf')
        d = {}
        index = 0
        e_list = []
        now_min = float('inf')
        while index < m:
            r_index = bisect.bisect_left(e_list, ans[index][0])
            if r_index > 0:
                min_len = min(min_len, d[e_list[r_index - 1]] + ans[index][1] - ans[index][0] + 1)
            now_min = min(now_min, ans[index][1] - ans[index][0] + 1)
            e_list.append(ans[index][1])
            d[ans[index][1]] = now_min
            index += 1
        if min_len == float('inf'):
            return -1
        return min_len


data = Solution()
arr = [7, 3, 4, 7]
target = 7
print(data.minSumOfLengths(arr, target))
arr = [4, 3, 2, 6, 2, 3, 4]
target = 6
print(data.minSumOfLengths(arr, target))
arr = [1, 2, 1]
target = 3
print(data.minSumOfLengths(arr, target))
